package com.iut.contactlist;

import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;

/**
 * Contains the contact list of the player.
 * @author coutinn
 * @see {@link Contact}
 */
public class ContactList {
	
	public static final String EMPTY_LIST_ERROR = "Contact list is empty !";

	private ArrayList<Contact> contacts;

	/**
	 * ContactList class constructor.
	 * @param c Application's context.
	 */
	public ContactList(Context c) throws ContactListException {

		this.contacts = new ArrayList<Contact>();

		// Test, uncomment to add these contacts :
		this.contacts.add(new Contact("test","0627071790"));
		this.contacts.add(new Contact("test2","0627071791"));
		this.contacts.add(new Contact("test3","0627071792"));
		this.contacts.add(new Contact("test4","0627071793"));

		// This code will get the contacts list of the player and will stock it into the <b>contacts</b> variable.

		Cursor cursor = c.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);

		while (cursor.moveToNext()) {

			Cursor people = c.getContentResolver().query(
					ContactsContract.Contacts.CONTENT_URI, null, null, null,
					null);
			while (people.moveToNext()) {
				this.contacts.add(new Contact(people.getString(people
						.getColumnIndex(PhoneLookup.DISPLAY_NAME)), people
						.getString(people.getColumnIndex(PhoneLookup.NUMBER))));
			}
			people.close();

		}
		cursor.close();

	}

	/**
	 * Returns a random contact from the contact list
	 * @return Random contact
	 */
	public Contact getRandomContact() throws ContactListException {
		if ( this.contacts.size() == 0 )
			throw new ContactListException(EMPTY_LIST_ERROR);
		int lower = 0; 						// Inclu
		int higher = this.contacts.size(); 	// Exclu
		int random = (int)(Math.random()*(higher-lower))+lower;
		return this.contacts.get(random);
	}

	/**
	 * Returns the contact list converted to String type.
	 * @return The contact list.
	 * <br/><b>Exemple :</b><br/>
	 *     <ul>
	 *         <li>Name : Batman. Number : 1337</li>
	 *         <li>Name : Joker. Number : 1664</li>
	 *     </ul>
	 */
	@Override
	public String toString() {
		String liste = "";
		for (Contact c : this.contacts) {
			liste += c.toString()+"\n";
		}
		return liste;
	}

	public ArrayList<Contact> getContacts() {
		return contacts;
	}

	public void setContacts(ArrayList<Contact> contacts) {
		this.contacts = contacts;
	}

}